
// require(moduleName)  moduleName 模块名称
// 服务器模块加载
const http = require("http");
// console.log(http);
const fs = require("fs");

// 加载了三方库 mysql
const mysql = require("mysql");
const artTemp = require("art-template");

// 服务器对象创建
const server = http.createServer(function(request,response){

    let conn =  mysql.createConnection({
        host:"localhost",
        user:"root",
        password:"",
        database:"films"
    });
    conn.connect();
    conn.query("select * from film limit 0,3",function(error,data,fields){
        response.setHeader("Content-Type","text/html;charset=utf-8");
        if(error){
            response.end("<h1 style='color:red'>服务器运行错误</h1>");
            return;
        }
        // console.log(error,data,fields);
        // console.log(data[0]);
        let source = fs.readFileSync("./template/home.html") // 读取指定路径的文件信息
        let temp = artTemp.render(source.toString(),{ list:data });

        // let temp = artTemp(__dirname+"/template/home.html",{
        //     list:data
        // })


        // response.write(JSON.stringify(data));
        response.end(temp);
    });
    conn.end();
});

// 服务器启动监听
server.listen(3000,function(){
    console.log("服务器启动成功，运行与 localhost:3000");
});